package com.maoye.ossp.common.web;

import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.BaseModel;
import com.hotent.base.api.Page;
import com.hotent.base.api.query.Direction;
import com.hotent.base.api.query.FieldSort;
import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.base.db.api.IdGenerator;
import com.hotent.base.db.model.DefaultQueryFilter;
import com.hotent.base.db.mybatis.domain.DefaultFieldSort;
import com.hotent.base.db.mybatis.domain.DefaultPage;
import com.maoye.ossp.common.util.DateUtils;
import com.maoye.ossp.common.util.ReflectionUtils;

/**
 * 控制器基类
 * 
 * @author zhuangwl
 * @date 2013-12-16
 * @version 1.0
 */
public class BaseController {

	@Resource
	public IdGenerator idGenerator;

	/*操作成功*/
	public static String SUCCESS = "/common/success";
	/*无权限操作*/
	public static String _403 = "/common/403";
	/*找不到界面*/
	public static String _404 = "/common/404";
	/*内部错误*/
	public static String _500 = "/common/500";
	
	/*开票成功*/
	public static String SUCCESS_TICKET = "/common/successTicket";

	/**
	 * 添加Model消息
	 * 
	 * @param message
	 */
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages) {
			sb.append(message).append(messages.length > 1 ? "<br/>" : "");
		}
		model.addAttribute("message", sb.toString());
	}

	/**
	 * 添加Flash消息
	 * 
	 * @param message
	 */
	protected void addMessage(RedirectAttributes redirectAttributes,
			String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages) {
			sb.append(message).append(messages.length > 1 ? "<br/>" : "");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils
						.escapeHtml4(text.trim()));
			}

			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
		});
	}

	protected String resultPage(String rtn, Model model,
			HttpServletRequest request) {
		if (model != null && request != null) {
			String navId = request.getParameter("navId");
			model.addAttribute("navId", navId);
			model.addAttribute("pageNo", request.getParameter("pageNo"));
		}
		return rtn;
	}

	/**
	 * 返回构建的QueryFilter
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	protected QueryFilter getQuerFilter(HttpServletRequest request,
			BaseModel model) {
		DefaultQueryFilter queryFilter = new DefaultQueryFilter();
		try {
			String pageSize = request.getParameter("pageSize");
			String pageNo = (String) request.getParameter("pageNo");
			// 设置查询字段
			setQueryParam(request, queryFilter, model);
			DefaultPage page = new DefaultPage(15);
			// 设置分页
			if (StringUtil.isNotEmpty(pageSize)) {
				page.setLimit(Integer.parseInt(pageSize));
			}
			if (StringUtil.isNotEmpty(pageNo)) {
				page.setPage(Integer.parseInt(pageNo));
			}
			queryFilter.setPage(page);
		
			// 设置排序字段
			String sort = request.getParameter("sort");
			String order = request.getParameter("order");
			if (StringUtil.isNotEmpty(sort) && StringUtil.isNotEmpty(order)) {
				List<FieldSort> fieldSorts = new ArrayList<FieldSort>();
				fieldSorts.add(new DefaultFieldSort(sort, Direction
						.fromString(order)));
				queryFilter.setFieldSortList(fieldSorts);
			}
		} catch (Exception e) {
		}
		return queryFilter;
	}

	/**
	 * 设置查询字段
	 * 
	 * @param request
	 * @param queryFilter
	 * @param model
	 */
	protected void setQueryParam(HttpServletRequest request,
			DefaultQueryFilter queryFilter, BaseModel model) {
		if (model != null) {
			Enumeration params = request.getParameterNames();
			while (params.hasMoreElements()) {
				String key = params.nextElement().toString();
				Object value = ReflectionUtils.getFieldValueByName(key, model);
				if (value != null && StringUtils.isNotBlank(value.toString())) {
					if (value instanceof Date) {
						value = DateUtils.formatDate((Date) value);
					}
					queryFilter.getParams().put(key, value);
				}
			}
		}
	}

	protected Page getPage(HttpServletRequest request) {
		DefaultPage page = new DefaultPage();
		try {
			String pageSize = request.getParameter("pageSize");
			String pageNo = (String) request.getParameter("pageNo");
			// 设置分页
			if (StringUtil.isNotEmpty(pageSize)
					&& StringUtil.isNotEmpty(pageNo)) {
				page.setLimit(Integer.parseInt(pageSize));
				page.setPage(Integer.parseInt(pageNo));
			}
		} catch (Exception e) {
		}
		return page;
	}
}
